#!/bin/sh

# Do not run as CGI
if [ -n "$GATEWAY_INTERFACE" ] ; then
    echo 'Can not invoke as CGI!'
    exit 1
fi

set -e
set -x

if [ "$CI_MODE" != "selenium" ] ; then
    echo "Not in CI_MODE=selenium"
    exit 0
fi

# Start php-fpm + nginx in temporary dir
DIR=`mktemp -d --suffix=-phpMyAdminTest`
CURRENT=`pwd`

# Create configuration with correct paths
cp tests/nginx.conf tests/php-fpm.conf tests/php.ini $DIR/
sed -i -e "s,%DIR%,$DIR," -e "s,%ROOT%,$CURRENT," $DIR/*
mkdir $DIR/sessions

echo "Using temporary dir: ${DIR}"

# You can define FPM_PATH to override the path for example FPM_PATH="php-fpm7.4"
FPM_PATH="${FPM_PATH:-php-fpm}"

# Start servers
"$FPM_PATH" --fpm-config $DIR/php-fpm.conf -c $DIR/php.ini
${NGINX_PATH:-nginx} -c $DIR/nginx.conf

if [ ! -z "$TESTSUITE_BROWSERSTACK_KEY" ] ; then
    echo "Using: BrowserStack"
    # Install if necessary
    if [ ! -f ~/browserstack/BrowserStackLocal ] ; then
        mkdir -p ~/browserstack
        cd ~/browserstack
        wget https://www.browserstack.com/browserstack-local/BrowserStackLocal-linux-x64.zip
        unzip BrowserStackLocal-linux-x64.zip
    fi
    # Start BrowserStack Local forwarder
    ~/browserstack/BrowserStackLocal --force-local --localIdentifier "gh-$GITHUB_ACTION" --onlyAutomate --key "$TESTSUITE_BROWSERSTACK_KEY" --daemon start
elif [ -z "$SKIP_STANDALONE" ] ; then
    echo "Using: selenium-standalone"
    if [ ! -f selenium-standalone ]; then
        yarn global add selenium-standalone
        selenium-standalone install
    fi
    selenium-standalone start -- -debug > ~/selenium-standalone.logs~ 2>&1 &
    echo $! > ~/selenium-standalone.pid~
else
    echo "Using: nothing."
fi

echo "${DIR}" > /tmp/last_temp_dir_phpMyAdminTests
